package cn.edu.nju.ws.sview.wyge.relations.adataset.overview.dataGet;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;

public class tripleInfo {
	public static ArrayList<triple> getTriple(
			HashMap<String, Integer> instanceIdToIndex,
			ArrayList<Integer> documents) throws ClassNotFoundException,
			SQLException {
		ArrayList<triple> triples = new ArrayList<triple>();
		Connection con = DBConnectionFactory.getConnection();//.getFalconConnection();
		HashMap<String, String> prop = new HashMap<String, String>();
		for (int i = 0; i < documents.size(); ++i) {
			// System.out.println(documents.get(i));
//			String query = "SELECT distinct(p) FROM quadruple where c = "
//					+ documents.get(i);
			String query = "SELECT distinct(p) FROM quadruple where doc_id = "
					+ documents.get(i);
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			while (rs.next()) {
				String uri = rs.getString(1);
				if (prop.containsKey(uri))
					continue;
				String p = "";
				String query1 = "SELECT uri FROM uri where id = "
						+ uri.substring(1);
				Statement st1 = con.createStatement();
				ResultSet rs1 = st1.executeQuery(query1);
				while (rs1.next()) {
					p = rs1.getString(1);
					p = Reduce.uri(p);
					break;
				}
				// System.out.println(uri + " " + p);
				prop.put(uri, p);
				rs1.close();
				st1.close();
			}
			rs.close();
			st.close();
		}
		/**/
		for (int i = 0; i < documents.size(); ++i) {
//			String query = "SELECT s, p, o FROM quadruple where c = "
//					+ documents.get(i);
			String query = "SELECT s, p, o FROM quadruple where doc_id = "
					+ documents.get(i);
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery(query);
			int typeid = 0;
			try {
				typeid = URIIDCache.getInstance().getURIID(
						"http://www.w3.org/1999/02/22-rdf-syntax-ns#type", false);
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			while (rs.next())
				if ((rs.getString(2).compareTo("u"+typeid) != 0)
						&& (instanceIdToIndex.containsKey(rs.getString(1)))
						&& (instanceIdToIndex.containsKey(rs.getString(3)))) {
					// System.out.println(instanceIdToIndex.get(rs.getString(1))
					// + " " + prop.get(rs.getString(2)) + " " +
					// instanceIdToIndex.get(rs.getString(3)));
					triple t = new triple();
					t.from = instanceIdToIndex.get(rs.getString(1));
					t.prop = prop.get(rs.getString(2));
					t.to = instanceIdToIndex.get(rs.getString(3));
					triples.add(t);
				}
			rs.close();
			st.close();
		}

		con.close();
		return triples;
	}
}
